import axios from 'axios'
import baseUrl from '@/config/baseUrl'
import { mockPrefix, useMock } from '@/config/settings'
import { ElMessage, ElNotification } from 'element-plus'

let baseURL = baseUrl
if (process.env.NODE_ENV === 'development' && useMock) {
  baseURL = mockPrefix
}
// 创建axios实例
const request = axios.create({
  baseURL,
  timeout: 60000 * 10,
  headers: {
    'Access-Control-Allow-Origin': '*',
    'Access-Control-Allow-Headers': 'X-Requested-With,Content-Type',
    'Access-Control-Allow-Methods': 'PUT,POST,GET,DELETE,OPTIONS',
    'Content-Type': 'application/json'
  },
  withCredentials: true //带上cookie
})

request.interceptors.response.use(
  (res) => {
    const code = res.data.code || 200
    const msg = res.data.msg
    const { method = '', custom = {} } = res.request
    const { url } = custom
    if (code == 200) {
      console.log(`%c${method} ${url} code:${code}:${msg}`, 'color:green', res.config.data, res.data)
    } else {
      console.log(`%c${method} ${url} code:${code}:${msg}`, 'color:#ff8400', res.config.data, res.data)
    }

    // 二进制数据则直接返回
    if (res.request.responseType === 'blob' || res.request.responseType === 'arraybuffer') {
      return res.data
    }
    if (code === 401) {
      location.href = '/login'
      return Promise.reject('无效的会话，或者会话已过期，请重新登录。')
    } else if (code === 500) {
      ElMessage({ message: msg, type: 'error' })
      return Promise.reject(new Error(msg))
    } else if (code === 601) {
      ElMessage({ message: msg, type: 'warning' })
      return Promise.reject(new Error(msg))
    } else if (code !== 200) {
      ElNotification.error({ title: msg })
      return Promise.reject('error')
    } else {
      return Promise.resolve(res.data.data)
    }
  },
  (error) => {
    let { message } = error
    if (message == 'Network Error') {
      message = '后端接口连接异常'
    } else if (message.includes('timeout')) {
      message = '系统接口请求超时'
    } else if (message.includes('Request failed with status code')) {
      message = '系统接口' + message.substr(message.length - 3) + '异常'
    }
    ElMessage({ message: message, type: 'error', duration: 5 * 1000 })
    return Promise.reject(error)
  }
)

export default request
